﻿package 
{
	
	/*
	 * In flashDevelop > Compiler Options > Advanced > Additional Compiler Options : -frame start Main
	 */

	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.utils.getDefinitionByName;
	import flash.display.Shape;
	
	public class Preloader extends MovieClip 
	{
		private var preloadShape:Shape;
		
		public function Preloader() 
		{
			addEventListener(Event.ENTER_FRAME, checkFrame);
			loaderInfo.addEventListener(ProgressEvent.PROGRESS, progress);
			// show loader
			preloadShape = new Shape();
			addChild(preloadShape);
		}
		
		private function progress(e:ProgressEvent):void 
		{
			// update loader
			trace("game loaded: " + Math.round(100*e.bytesLoaded / e.bytesTotal) + " %   [" + e.bytesLoaded + "/" + e.bytesTotal + "]");
			
			preloadShape.graphics.clear();
			preloadShape.graphics.lineStyle(1);
			preloadShape.graphics.drawRect(10, 10, 110, 5);
			preloadShape.graphics.beginFill(0);
			preloadShape.graphics.drawRect(10, 10, 10 + (e.bytesLoaded / e.bytesTotal) * 100, 5);
			//preloadShape.graphics.beginFill(0x0000FF);
			preloadShape.graphics.endFill();
		}
		
		private function checkFrame(e:Event):void 
		{
			if (currentFrame == totalFrames) 
			{
				removeEventListener(Event.ENTER_FRAME, checkFrame);
				startup();
			}
		}
		
		private function startup():void 
		{
			// hide loader
			stop();
			//removeChild(preloadShape);
			loaderInfo.removeEventListener(ProgressEvent.PROGRESS, progress);
			var mainClass:Class = getDefinitionByName("Main") as Class;
			addChild(new mainClass() as DisplayObject);
		}
		
	}
	
}